package com.pan.kang.core;


import java.lang.annotation.Annotation;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class DecoratorProxy implements InvocationHandler {

    private final Object target;

    public DecoratorProxy(Object target) {
        this.target = target;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        Object result = method.invoke(target, args);
        run(target, method);
        return result;
    }

    public Object getProxy() {
        return Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(),
                target.getClass().getInterfaces(), this);
    }

    private void run(Object target, Method method) {
        try {
            Annotation[] annotations = target.getClass().getMethod(method.getName(),
                    method.getParameterTypes()).getAnnotations();
            for (Annotation annotation : annotations) {
                if (annotation.annotationType().isAssignableFrom(Flow.class)) {
                    DecoratorInterface decoratorInterface = (DecoratorInterface) target;
                    Flow flow = (Flow) annotation;
                    switch (flow.step()) {
                        case history:
                            decoratorInterface.history();
                            break;
                    }
                }
            }
        } catch (Exception exception) {
            throw new RuntimeException(exception);
        }
    }
}
